package com.phonemap;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.phonemap.common.Util;
import com.phonemap.models.User;

@SuppressWarnings("serial")
public class LoginServlet extends BaseServlet {
	private static final Logger logger = Logger.getLogger(LoginServlet.class
			.getCanonicalName());
	
	/**
	 * Get the requested photo entities in JSON format
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doGet(req, resp);
		logger.log(Level.INFO, "Obtaining User listing");
		String action = req.getParameter("action");
		PrintWriter out = resp.getWriter();
		if (action.equalsIgnoreCase("checkaccount")) {
			String phone = req.getParameter("phone");
			String email = req.getParameter("email");
			List<Entity> entities = new ArrayList<Entity>();
			Entity entity = User.getUser(phone);
			if(entity != null)
				entities.add(entity);
			Iterable<Entity> listEntity = User.getUsers("email", email);
			if (listEntity != null) {
				if (listEntity.iterator().hasNext()) 
					entities.add(listEntity.iterator().next());
			}
			out.println(Util.writeJSON(entities));
		} else if (action.equalsIgnoreCase("login")) {
			String phone = req.getParameter("phone");
			String password = req.getParameter("password");
			Entity entity = User.getUser(phone);
			List<Entity> entities = new ArrayList<Entity>();
			if (entity != null) {
				if (password.equals(entity.getProperty("password").toString())) {
					entities.add(entity);
				}
			}
			out.println(Util.writeJSON(entities));
		}
		
		return;
	}

	/**
	 * Insert the new customer
	 */
	protected void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		logger.log(Level.INFO, "Creating User");
		
		String phone = req.getParameter("phone");
		String email = req.getParameter("email");
		String password = req.getParameter("password");
		User.createOrUpdateUser(phone, null, null, email, password,
				null);
	}

	/**
	 * Delete the customer
	 */
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String phone = req.getParameter("id");
		logger.log(Level.INFO, "Deleting User {0}", phone);
		Key key = KeyFactory.createKey("User", phone);
		try {
			// CASCADE_ON_DELETE
			Iterable<Entity> entities = Util.listChildKeys("Position", key);
			final List<Key> positionkeys = new ArrayList<Key>();
			for (Entity e : entities) {
				positionkeys.add(e.getKey());

			}
			Util.deleteEntity(positionkeys);
			Util.deleteFromCache(key);
			Util.deleteEntity(key);
		} catch (Exception e) {
			String msg = Util.getErrorResponse(e);
			resp.getWriter().print(msg);
		}
	}

	/**
	 * Redirect the call to doDelete or doPut method
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String action = req.getParameter("action");
		if (action.equalsIgnoreCase("delete")) {
			doDelete(req, resp);
			return;
		} else if (action.equalsIgnoreCase("put")) {
			doPut(req, resp);
			return;
		}
	}
	
	
}
